<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow">
        <div>
          <a-form
            ref="formRef"
            size="small"
            layout="inline"
            :model="pageData"
            v-if="
              permissionStore.hasPermisson('jzrgzmx.cx') || permissionStore.hasPermisson('jzygz.cx')
            "
          >
            <a-form-item v-if="id == 2" label="月份">
              <a-month-picker
                :style="{ width: '200px' }"
                class="bacClass"
                v-model="pageData.month"
                @press-enter="huiche"
              />
            </a-form-item>
            <!-- <a-form-item label-col-flex="80px" label="月份">
                        <a-select popup-container="html"  :style="{ width: '267px' }" class="bacClass">
                            <a-option v-for="item in months">{{ item }}</a-option>
                        </a-select>
                    </a-form-item> -->
            <a-form-item v-else label="日期">
              <!-- <a-date-picker  popup-container="html"  style="width:150px" class="bacClass" v-model="pageData.dates" @press-enter="huiche" />至
                            <a-date-picker  popup-container="html"  style="width:150px" class="bacClass" v-model="pageData.dates2" @press-enter="huiche" /> -->
              <a-range-picker
                popup-container="html"
                :style="{ width: '250px' }"
                class="bacClass"
                @select="onSelect"
                @press-enter="huiche"
                @clear="onClear"
              />
            </a-form-item>
            <a-form-item label="岗位">
              <a-select
                popup-container="html"
                style="width: 200px"
                class="bacClass"
                v-model="pageData.post"
                :filter-option="false"
                @press-enter="huiche"
                multiple
              >
                <a-option value="全部">全部</a-option>
                <a-option value="值机">值机</a-option>
                <a-option value="搬运">搬运</a-option>
                <a-option value="机修">机修</a-option>
                <a-option value="验布">验布</a-option>
                <a-option value="拆纱">拆纱</a-option>
                <a-option value="翻纱">翻纱</a-option>
                <a-option value="倒纱">倒纱</a-option>
              </a-select>
              <!-- <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                                v-model="pageData.post" @press-enter="huiche" /> -->
            </a-form-item>
            <a-form-item label="员工工号">
              <!-- <a-select popup-container="html"  class="bacClass" v-model="pageData.empNo" @focus="focusSel3" allow-clear>
                            <a-option :style="{ width: '200px' }" v-for="item in pageData.xmList" :value="item.empNo">
                                {{ item.empNo }}
                            </a-option>
                        </a-select> -->
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                placeholder=""
                v-model="pageData.empCode"
                @press-enter="huiche"
              />
            </a-form-item>
            <a-form-item label="员工姓名">
              <!-- <a-select popup-container="html"  class="bacClass" v-model="pageData.empName" @focus="focusSel3" allow-clear>
                            <a-option :style="{ width: '200px' }" v-for="item in pageData.xmList" :value="item.empName">
                                {{ item.empName }}
                            </a-option>
                        </a-select> -->
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                placeholder=""
                v-model="pageData.empName"
                @press-enter="huiche"
              />
            </a-form-item>
          </a-form>
        </div>
        <div class="my-tool-bar">
          <Toolbar
            :items="pageData.btnList"
            @add="addHandler"
            @import="importHandler"
            @del="deleteHandler"
            @select="selectHandler"
            @export="exports"
          >
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
    </template>
    <template #pageTabel>
      <!-- <div class="my-tool-bar" style="margin-right: 10px;margin-bottom: -40px;">
                <a-button size="mini" style=" margin:5px; " @click="CentralAudit" type="primary">中控审核</a-button>
                <a-button size="mini" style="margin: 5px;" @click="deleteHandler" type="primary">删除</a-button>
            </div> -->
      <a-tabs :lazy-load="true" :justify="true" default-active-key="1" @change="handoff">
        <a-tab-pane title="计件日工资明细" key="1">
          <AgGridVuesCopys
            :rowHeight="33"
            :headerHeight="33"
            :suppressCopyRowsToClipboard="true"
            rowSelection="multiple"
            @grid-ready="gridReady"
            style="height: 100%"
            :defaultColDef="defaultColDef"
            class="ag-theme-alpine"
            :rowData="pageData.tableList"
            :columnDefs="tc"
            :localeText="localeText1"
            @FilterChanged="FilterChangeds"
          ></AgGridVuesCopys>
        </a-tab-pane>
        <a-tab-pane title="计件月工资" key="2">
          <AgGridVuesCopys
            :rowHeight="33"
            :headerHeight="33"
            rowSelection="multiple"
            @grid-ready="gridReady2"
            style="height: 100%"
            :defaultColDef="defaultColDef"
            class="ag-theme-alpine"
            :rowData="pageData.tableList2"
            :columnDefs="tc2"
            :localeText="localeText1"
            @FilterChanged="FilterChangeds"
          ></AgGridVuesCopys>
        </a-tab-pane>
      </a-tabs>
    </template>
    <!-- <paginationCopys :page-size="size" :current="page" :total="total" show-total show-jumper show-page-size
            @change="PageSize" @page-size-change="change1" style="justify-content: center" /> -->
    <a-drawer
      ok-text="保存"
      cancel-text="关闭"
      :drawer-style="{ zIndex: 9999 }"
      :mask-closable="false"
      :width="400"
      :ok-loading="pageData.pageLoading"
      :visible="pageData.showAdd"
      unmountOnClose
      @ok="sideOk"
      @cancel="pageData.showAdd = false"
    >
      <template #title>
        {{ pageData.sideTitle }}
      </template>
    </a-drawer>
  </pageTabelLayout>
</template>

<script lang="ts">
  import { post } from '@/api/http'
  import {
    useTable,
    useRowKey,
    useTableColumn,
    usePagination,
    useRowSelection,
  } from '@/hooks/table'
  import emitter from '@/hooks/useEventBus'
  import { ref, reactive, onMounted, toRefs } from 'vue'
  import Toolbar from '@/components/Toolbar.vue'
  import { Form, Message, Modal } from '@arco-design/web-vue'
  import { FormInstance } from '@arco-design/web-vue/es/form'
  import { baseURL } from '../../../api/axios.config'
  import axios from 'axios'
  import filedownload from 'js-file-download'
  import usePermission from '@/store/modules/permission'
  import PageTabelLayout from '@/components/pageTabelLayout.vue'
  import { AnyARecord } from 'dns'
  import setTableTotalRow from '@/utils/setTableTotalRow.ts'
  import { localeText } from '@/api/aggridZw'
  import WHService, { Warhouse, CompanyList, WhTypeField } from '@/service/wh'
  import { messageConfig } from 'element-plus'
  import { keyBy } from 'lodash'

  interface BrandInfo {
    id: any
    remark: any
    createName: string | undefined
    createTime: string | undefined
    updateName: string | undefined
    updateTime: string | undefined
    deleteState: any
    obsoleteState: any
    serialNumber: any
    materialName: any
    materialCode: any
    foremanTechnology: any
    straight: any
    bathe: any
    maxValues: any
    hACacidity: any
    stockNumber: any
    jobType: any
  }

  export default {
    name: 'EmployeeSeniorityReport',
    setup() {
      const handoff = (key: any) => {
        id.value = key
        if (id.value == 1) {
          pageData.dutymachineState = 0
          // doRefresh();
        } else {
          pageData.dutymachineState = 1
          // doRefresh2();
        }
      }
      let id = ref(1)
      const total = ref(10)
      const page = ref(1)
      const size = ref(10)
      function PageSize(val: any) {
        if (id.value == 1) {
          page.value = val
          doRefresh()
        } else {
          page.value = val
          doRefresh2()
        }
      }
      function change1(val: any) {
        if (id.value == 1) {
          size.value = val
          doRefresh()
        } else {
          size.value = val
          doRefresh2()
        }
      }
      const headerShow = ref<boolean>(true)
      const toFixedNum = (num: number) => {
        return parseFloat(num.toFixed(2))
      }
      //查询方法
      function doRefresh() {
        if (pageData.dates == '' || pageData.dates2 == '' || pageData.post == '') {
          Message.warning('请先选择日期和岗位')
          return
        } else {
          post({
            url: '/pieceData/adjustmentEmpInfo/getPieceWage',
            data: {
              // "page": page.value,
              // "size": size.value,
              postName: pageData.post,
              deleteState: '0',
              beginDate: pageData.dates,
              endDate: pageData.dates2,
              userCode: pageData.empCode,
              userName: pageData.empName,
            },
          })
            .then(({ data, code }: any) => {
              if (code === 200) {
                pageData.tableList = data
                gridOption.value.setRowData(data)
                gridOption.value.sizeColumnsToFit()
                if(pageData.tableList.length > 0){
                  countRow(pageData.tableList)
                }
              }
            })
            .catch(console.log)
            .finally(() => {
              pageData.pageLoading = false
            })
        }
      }
      function doRefresh2() {
        if (pageData.month == '' || pageData.post == '') {
          Message.warning('请先选择月份和岗位')
          return
        } else {
          post({
            url: '/pieceData/adjustmentEmpInfo/getPieceWage',
            data: {
              // "page": page.value,
              // "size": size.value,
              postName: pageData.post,
              deleteState: '0',
              queryMonth: pageData.month,
              userCode: pageData.empCode,
              userName: pageData.empName,
            },
          })
            .then(({ data, code }: any) => {
              if (code === 200) {
                pageData.tableList2 = data
                gridOption2.value.setRowData(data)
                gridOption2.value.sizeColumnsToFit()
                if(pageData.tableList2.length > 0){
                  countRow(pageData.tableList2)
                }
              }
            })
            .catch(console.log)
            .finally(() => {
              pageData.pageLoading = false
            })
        }
      }
      const { selectedRowKeys, onSelectionChange } = useRowSelection()
      const pagination = usePagination(doRefresh)
      const table = useTable()
      const rowKey = useRowKey('id')
      const tableColumns1 = useTableColumn([
        {
          title: '公司',
          key: 'companyName',
          dataIndex: 'companyName',
          width: 160,
        },
        {
          title: '计件日期',
          key: 'pieceDate',
          dataIndex: 'pieceDate',
          width: 160,
        },
        {
          title: '员工工号',
          key: 'userCode',
          dataIndex: 'userCode',
          width: 160,
        },
        {
          title: '员工姓名',
          key: 'userName',
          dataIndex: 'userName',
          width: 160,
        },
        {
          title: '岗位',
          key: 'postName',
          dataIndex: 'postName',
          width: 160,
        },
        {
          title: '计件总金额',
          key: 'pieceWage',
          dataIndex: 'pieceWage',
          width: 160,
        },
        {
          title: '乐捐金额',
          key: 'donateAmount',
          dataIndex: 'donateAmount',
          width: 160,
        },
        {
          title: '生产补贴金额',
          key: 'produceSubsidyAmount',
          dataIndex: 'produceSubsidyAmount',
          width: 160,
        },
        {
          title: '织布单补贴金额',
          key: 'planOrderSubsidyAmount',
          dataIndex: 'planOrderSubsidyAmount',
          width: 160,
        },
        {
          title: '应得金额',
          key: 'pieceWageAmount',
          dataIndex: 'pieceWageAmount',
          width: 160,
        },
      ])
      const tableColumns2 = useTableColumn([
        {
          title: '公司',
          key: 'companyName',
          dataIndex: 'companyName',
          width: 160,
        },
        {
          title: '计件月份',
          key: 'pieceDate',
          dataIndex: 'pieceDate',
          width: 160,
        },
        {
          title: '员工工号',
          key: 'userCode',
          dataIndex: 'userCode',
          width: 160,
        },
        {
          title: '员工姓名',
          key: 'userName',
          dataIndex: 'userName',
          width: 160,
        },
        {
          title: '岗位',
          key: 'postName',
          dataIndex: 'postName',
          width: 160,
        },
        {
          title: '计件总金额',
          key: 'pieceWage',
          dataIndex: 'pieceWage',
          width: 160,
        },

        {
          title: '乐捐金额',
          key: 'donateAmount',
          dataIndex: 'donateAmount',
          width: 160,
        },
        {
          title: '生产补贴金额',
          key: 'produceSubsidyAmount',
          dataIndex: 'produceSubsidyAmount',
          width: 160,
        },
        {
          title: '织布单补贴金额',
          key: 'planOrderSubsidyAmount',
          dataIndex: 'planOrderSubsidyAmount',
          width: 160,
        },
        {
          title: '应得金额',
          key: 'pieceWageAmount',
          dataIndex: 'pieceWageAmount',
          width: 160,
        },
      ])
      let tc: any[] = tableColumns1.map((o) => {
        let obj = {
          headerName: o.title,
          field: o.key,
          pinned: o['fixed'],
          tooltipField: o.key,
        }
        return obj
      })
      let tc2: any[] = tableColumns2.map((o) => {
        let obj = {
          headerName: o.title,
          field: o.key,
          pinned: o['fixed'],
          tooltipField: o.key,
        }
        return obj
      })
      let a = [
        {
          showRowGroup: 'hide_def',
          headerName: '',
          checkboxSelection: true,
          headerCheckboxSelection: true,
          pinned: 'left',
          width: 60,
          resizable: false,
          filter: false,
          sortable: false,
          minWidth: 60,
          maxWidth: 60,
          lockPosition: 'left',
        },
      ]
      tc = a.concat(tc)
      tc2 = a.concat(tc2)

      const pageData = reactive<{
        showAdd: boolean
        sideTitle: string
        dropDownData: any
        nameList: []
        pageLoading: boolean
        typeList: []
        dropDownData1: any
        rHeight: any
        btnList: any[]
        isEdit: boolean
        wlList: []
        isLxs: boolean
        CodeNameList: []
        bgNameList: any[]
        dutymachineState: number | undefined
        month: any
        dates: any
        dates2: any
        post: any
        empCode: any
        empName: any
        hejishuzu: any
        tableList:any[]
        tableList2:any[]
      }>({
        tableList2:[],
        tableList:[],
        nameList: [],
        showAdd: false,
        sideTitle: '新增导入中控中转检查站',
        dropDownData: '',
        pageLoading: false,
        typeList: [],
        dropDownData1: '',
        rHeight: 0,
        btnList: [],
        isEdit: false,
        wlList: [],
        isLxs: false,
        CodeNameList: [],
        bgNameList: [],
        dutymachineState: 0,
        month: '',
        dates: '',
        dates2: '',
        post: ['全部'],
        empCode: '',
        empName: '',
        hejishuzu: [],
      })

      interface gcType {
        id: any
        company: any
      }
      //下拉框得到焦点
      const focusSel = () => {
        selCxAll({ formulaOdd: '' })
      }
      //下拉数据
      const options = ref<any>(pageData.nameList)
      const loading = ref(false)
      const handleSearch = (value: any) => {
        if (value) {
          const ob = { formulaOdd: value, deleteState: 0 }
          loading.value = true
          selCxAll(ob)
          options.value = pageData.nameList
          loading.value = false
        } else {
          options.value = []
        }
      }
      //下拉框查询
      function selCxAll(val: any) {
        post({
          url: '/pdm/TransitInspect/getFieldValue',
          data: val,
        }).then(({ data, code }: any) => {
          if (code === 200) {
            let dataList: any = []
            data.forEach(function (o: any) {
              dataList.push(o['formulaOdd'])
            })
            pageData.nameList = dataList
          } else {
            Message.error({
              content: '查询失败！',
              duration: 6000,
            })
          }
        })
      }
      onMounted(() => {
        // 第一个页面需要在刚进入就调用一次  切换tap时也需要调用
        // doRefresh();
        // 切换tap到本页面执行的方法
        emitter.on('EmployeeSeniorityReport', () => {
          if (id.value == 1) {
            doRefresh()
            gridOption.value.sizeColumnsToFit()
          } else if (id.value == 2) {
            doRefresh2()
            gridOption2.value.sizeColumnsToFit()
          }
        })
      })

      let cxbl = {}
      //查询
      const selectHandler = () => {
        if (id.value == 1) {
          doRefresh()
        } else if (id.value == 2) {
          doRefresh2()
        }
      }
      const queryData = reactive({
        materialName: '',
      })
      const addHandler = () => {
        for (var key in dataForm) {
          if (key === 'id') {
            dataForm[key] = null
          } else {
            dataForm[key] = ''
          }
        }
        dataForm.straight = false
        pageData.showAdd = true
        pageData.sideTitle = '新增导入中控中转检查站'
      }
      const dataForm = reactive<BrandInfo>({
        id: null,
        remark: '',
        createName: '',
        createTime: '',
        updateName: '',
        updateTime: '',
        deleteState: 0,
        obsoleteState: '',
        serialNumber: 0,
        materialName: null,
        foremanTechnology: '',
        straight: false,
        hACacidity: null,
        bathe: null,
        maxValues: null,
        stockNumber: '',
        materialCode: '',
        jobType: '',
      })

      // 表格准备事件
      const gridOption = ref()
      const gridReady = (params: any) => {
        gridOption.value = params.api
        gridOption.value.sizeColumnsToFit()
      }
      const gridOption2 = ref()
      const gridReady2 = (params: any) => {
        gridOption2.value = params.api
        gridOption2.value.sizeColumnsToFit()
      }
      const formRef = ref<FormInstance>()
      const sideOk = () => {
        formRef.value?.validate().then((err) => {
          if (!err) {
            formRef.value?.validate().then((err) => {
              if (!err) {
                pageData.pageLoading = true
                if (pageData.sideTitle === '新增导入中控中转检查站') {
                  post({
                    url: '/pdm/JobType/insert',
                    data: [dataForm],
                  })
                    .then((res: any) => {
                      if (res.code === 200) {
                        formRef.value?.resetFields()
                        pageData.showAdd = false
                        Message.success({
                          content: '新增成功',
                          duration: 6000,
                        })
                      } else {
                        Message.error({
                          content: res.message,
                          duration: 6000,
                        })
                      }
                      doRefresh()
                    })
                    .finally(() => {
                      doRefresh()
                      pageData.pageLoading = false
                    })
                } else {
                  post({
                    url: '/pdm/JobType/update',
                    data: [dataForm],
                  })
                    .then((res: any) => {
                      if (res.code === 200) {
                        formRef.value?.resetFields()
                        pageData.showAdd = false
                        Message.success({
                          content: '修改成功',
                          duration: 6000,
                        })
                      } else {
                        Message.error({
                          content: res.message,
                          duration: 6000,
                        })
                      }
                      //doRefresh();
                    })
                    .finally(() => {
                      doRefresh()
                      pageData.pageLoading = false
                    })
                }
              }
            })
          }
        })
      }
      const deleteHandler = () => {
        if (gridOption.value.getSelectedRows().length === 0) {
          Message.error('请先勾选')
          return
        }
        Modal.confirm({
          title: '系统提示',
          content: '确认删除选中的数据?',
          onOk() {
            pageData.pageLoading = true
            post({
              url: '/pdm/TransitInspect/delete',
              data: gridOption.value.getSelectedRows().map((o: any) => {
                return o.id
              }),
            })
              .then(({ code, data }: any) => {
                if (code === 200) {
                  Message.success({
                    content: '删除成功',
                    duration: 6000,
                  })
                  pagination.page = 1
                  doRefresh()
                } else {
                  Message.error({
                    content: '修改失败',
                    duration: 6000,
                  })
                }
              })
              .finally(() => {
                pageData.pageLoading = false
              })
          },
        })
      }
      const editHandler = (record: BrandInfo) => {
        //循环对象 赋值
        for (let key in record) {
          dataForm[key] = record[key]
        }
        if (dataForm.straight == 1) {
          dataForm.straight = true
        } else {
          dataForm.straight = false
        }
        pageData.sideTitle = '修改导入中控中转检查站'
        pageData.showAdd = true
      }
      //判断是否填写了中文
      const isChiese = (value: string, cb: Function) => {
        return new Promise<void>((resolve) => {
          if (window.encodeURI(value).indexOf('%') !== -1) {
            cb('填写的值只能是英文数字组合或英文，数字！')
          }
          resolve()
        })
      }
      //input离开焦点 将小写转大写
      const inputBlur = () => {}
      //导出
      const exports = () => {
        // if (id.value == 1) {
        //   // let idList: any = []
        //   // gridOption.value.getSelectedRows().forEach(function (o: any) {
        //   //   idList.push(o['id'])
        //   // })
        //   //将表头拼接出来
        //   let head =
        //     '<th>计件日期</th><th>员工工号</th><th>员工姓名</th><th>岗位</th><th>计件金额</th><th>增补乐捐金额</th><th>应得金额</th>'
        //   //拿到当前表格数据与勾选的行做筛选
        //   let nowRow = pageData.tableList
        //   // let nowRow = pageData.tableList.filter(function (o) {
        //   //   return (
        //   //     gridOption.value
        //   //       .getSelectedRows()
        //   //       .map((o: any) => {
        //   //         return o.id
        //   //       })
        //   //       .indexOf(o['id']) !== -1
        //   //   )
        //   // })
        //   let body = ''
        //   nowRow.forEach(function (o) {
        //     body += '<tr><td>' + (o['billDate'] == undefined ? '' : o['billDate']) + '</td>'
        //     body += '<td>' + (o['empCode'] == undefined ? '' : o['empCode']) + '</td>'
        //     body += '<td>' + (o['empName'] == undefined ? '' : o['empName']) + '</td>'
        //     body += '<td>' + (o['post'] == undefined ? '' : o['post']) + '</td>'
        //     body += '<td>' + (o['amount'] == undefined ? '' : o['amount']) + '</td>'
        //     body += '<td>' + (o['ljMoney'] == undefined ? '' : o['ljMoney']) + '</td>'
        //     body += '<td>' + (o['ydMoney'] == undefined ? '' : o['ydMoney']) + '</td>'
        //     body += '</tr>'
        //   })
        //   tableToXlsx(head, '计件日工资明细', body)
        // } else if (id.value == 2) {
        //   // let idList: any = []
        //   // gridOption2.value.getSelectedRows().forEach(function (o: any) {
        //   //   idList.push(o['id'])
        //   // })
        //   //  将表头拼接出来
        //   let head =
        //     '<th>月份</th><th>员工工号</th><th>员工姓名</th><th>岗位</th><th>计件总金额</th><th>增补乐捐总金额</th><th>应得总金额</th>'
        //   //拿到当前表格数据与勾选的行做筛选
        //   let nowRow = pageData.tableList
        //   // let nowRow = pageData.tableList.filter(function (o) {
        //   //   return (
        //   //     gridOption2.value
        //   //       .getSelectedRows()
        //   //       .map((o: any) => {
        //   //         return o.id
        //   //       })
        //   //       .indexOf(o['id']) !== -1
        //   //   )
        //   // })
        //   let body = ''
        //   nowRow.forEach(function (o) {
        //     body += '<tr><td>' + (o['billDate'] == undefined ? '' : o['billDate']) + '</td>'
        //     body += '<td>' + (o['empCode'] == undefined ? '' : o['empCode']) + '</td>'
        //     body += '<td>' + (o['empName'] == undefined ? '' : o['empName']) + '</td>'
        //     body += '<td>' + (o['post'] == undefined ? '' : o['post']) + '</td>'
        //     body += '<td>' + (o['amount'] == undefined ? '' : o['amount']) + '</td>'
        //     body += '<td>' + (o['ljMoney'] == undefined ? '' : o['ljMoney']) + '</td>'
        //     body += '<td>' + (o['ydMoney'] == undefined ? '' : o['ydMoney']) + '</td>'
        //     body += '</tr>'
        //   })
        //   tableToXlsx(head, '计件月工资', body)
        // }
        var param = {}
        var excelName = ''
        if (id.value == 1) {
          param = {
            // "page": page.value,
            // "size": size.value,
            postName: pageData.post,
            deleteState: '0',
            beginDate: pageData.dates,
            endDate: pageData.dates2,
            userCode: pageData.empCode,
            userName: pageData.empName,
          }
          excelName = '计件日工资明细'
        } else {
          param = {
            // "page": page.value,
            // "size": size.value,
            postName: pageData.post,
            deleteState: '0',
            queryMonth: pageData.month,
            userCode: pageData.empCode,
            userName: pageData.empName,
          }
          excelName = '计件月工资'
        }
        post({
          url: 'pieceData/adjustmentEmpInfo/exportAllPieceWage',
          data: param,
          responseType: 'blob',
        }).then((res: any) => {
          filedownload(res, excelName + '.xlsx')
        })
      }

      function tableToXlsx(head: any, filename: any, body: any) {
        const uri = 'data:application/vnd.ms-excel;base64,',
          template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`

        const a = document.createElement('a')
        a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
        a.download = filename
        a.click()
        document.removeChild(a)
      }

      //模板下载
      const downloadHandler = () => {
        axios
          .get(baseURL + '/pdm/formulaDose/uploadModel', {
            responseType: 'blob',
            headers: {
              token: sessionStorage.getItem('USER-TOKEN-KEY'),
            },
          })
          .then((res) => {
            if (res.status === 200) {
              filedownload(res.data, '导入中控中转检查站定义.xlsx')
            }
          })
      }
      //导入
      const importHandler = () => {
        const inputEle: HTMLInputElement = document.createElement('input')
        inputEle.type = 'file'
        inputEle.id = 'fileUploadExcel'
        inputEle.accept =
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
        inputEle.addEventListener('change', (e) => {
          const formData = new FormData()
          if (inputEle.files !== null) {
            formData.append('file', inputEle.files[0] || '')
          } else {
            Message.warning('未选择文件！')
            return
          }
          pageData.pageLoading = true
          axios
            .post(baseURL + '/pdm/formulaDose/importModelData', formData, {
              headers: {
                'Content-Type': 'multipart/form-data',
                token: sessionStorage.getItem('USER-TOKEN-KEY'),
              },
            })
            .then((result) => {
              if (result.data['code'] === 200) {
                Message.success('导入成功')
              } else {
                Message.error(result.data.message)
              }
            })
            .finally(() => {
              pageData.pageLoading = false
              doRefresh()
            })
        })
        inputEle.click()
      }
      const handleChange = (_data: any) => {
        table.handleSuccess(_data)
      }
      const defaultColDef = {
        sortable: true,
        resizable: true,
        filter: true,
      }
      const months = ref(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'])
      const localeText1: any = ref(localeText)
      const huiche = () => {
        if (id.value == 1) {
          doRefresh()
        } else {
          doRefresh2()
        }
      }
      const onSelect = (dateString: any) => {
        if (dateString[0]) {
          const d1 = new Date(dateString[0])
          const d2 = new Date(dateString[1])
          if (d1 > d2) {
            dateString.reverse()
          }
        }
        pageData.dates = dateString[0]
        pageData.dates2 = dateString[1]
      }
      const onClear = () => {
        pageData.dates = ''
        pageData.dates2 = ''
      }
      // :items="['查询', '导出']"
      const permissionStore = usePermission()
      if (permissionStore.hasPermisson('jzrgzmx.cx') || permissionStore.hasPermisson('jzygz.cx')) {
        pageData.btnList.push('查询')
      }
      if (permissionStore.hasPermisson('jzrgzmx.dc') || permissionStore.hasPermisson('jzygz.dc')) {
        pageData.btnList.push('导出')
      }
      const countRow = (data: any) => {
        if (id.value == 1) {
          setTableTotalRow(gridOption, data, [
            'pieceWage',
            'donateAmount',
            'produceSubsidyAmount',
            'planOrderSubsidyAmount',
            'pieceWageAmount',
          ])
        } else if (id.value == 2) {
          setTableTotalRow(gridOption2, data, [
            'pieceWage',
            'donateAmount',
            'produceSubsidyAmount',
            'planOrderSubsidyAmount',
            'pieceWageAmount',
          ])
        }
      }
      //筛选
      const FilterChangeds = (params: any) => {
        let data: any = {
          list: [],
        }
        params.api.forEachNodeAfterFilter((row: any) => {
          data.list.push(row.data)
        })
        countRow(data.list)
      }
      return {
        FilterChangeds,
        countRow,
        onSelect,
        onClear,
        huiche,
        months,
        id,
        handoff,
        localeText1,
        editHandler,
        deleteHandler,
        sideOk,
        formRef,
        dataForm,
        addHandler,
        selectedRowKeys,
        pagination,
        tableColumns1,
        tableColumns2,
        table,
        rowKey,
        pageData,
        queryData,
        selectHandler,
        isChiese,
        inputBlur,
        exports,
        options,
        loading,
        handleSearch,
        focusSel,
        downloadHandler,
        importHandler,
        headerShow,
        handleChange,
        PageSize,
        change1,
        defaultColDef,
        tc,
        tc2,
        gridOption,
        gridOption2,
        gridReady,
        gridReady2,
        total,
        page,
        size,
        WHService,
        permissionStore,
        toFixedNum,
      }
    },
    components: { Toolbar, PageTabelLayout,  },
  }
</script>
